<template>
  <a-modal
    title="半成品销售订单详情"
    :width="1400"
    :visible="visible"
    :footer="null"
    @cancel="handleCancel">
    
    <a-spin :spinning="loading">
      <div class="detail-container">
        
        <!-- 基本信息 -->
        <a-card title="基本信息" size="small" style="margin-bottom: 16px;">
          <a-row :gutter="24">
            <a-col :span="8">
              <div class="detail-item">
                <span class="detail-label">订单编号:</span>
                <span class="detail-value">{{ orderInfo.orderNo }}</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="detail-item">
                <span class="detail-label">客户名称:</span>
                <span class="detail-value">{{ orderInfo.customerName }}</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="detail-item">
                <span class="detail-label">项目名称:</span>
                <span class="detail-value">{{ orderInfo.projectName }}</span>
              </div>
            </a-col>
          </a-row>
          
          <a-row :gutter="24" style="margin-top: 16px;">
            <a-col :span="8">
              <div class="detail-item">
                <span class="detail-label">订单日期:</span>
                <span class="detail-value">{{ orderInfo.orderDate }}</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="detail-item">
                <span class="detail-label">交货日期:</span>
                <span class="detail-value">{{ orderInfo.deliveryDate }}</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="detail-item">
                <span class="detail-label">紧急程度:</span>
                <a-tag :color="getUrgencyColor(orderInfo.urgencyLevel)">
                  {{ getUrgencyText(orderInfo.urgencyLevel) }}
                </a-tag>
              </div>
            </a-col>
          </a-row>

          <a-row :gutter="24" style="margin-top: 16px;">
            <a-col :span="8">
              <div class="detail-item">
                <span class="detail-label">订单状态:</span>
                <a-tag :color="getStatusColor(orderInfo.status)">
                  {{ getStatusText(orderInfo.status) }}
                </a-tag>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="detail-item">
                <span class="detail-label">订单金额:</span>
                <span class="detail-value amount">¥{{ (orderInfo.totalAmount || 0).toFixed(2) }}</span>
              </div>
            </a-col>
            <a-col :span="8">
              <div class="detail-item">
                <span class="detail-label">已付金额:</span>
                <span class="detail-value amount">¥{{ (orderInfo.paidAmount || 0).toFixed(2) }}</span>
              </div>
            </a-col>
          </a-row>

          <a-row :gutter="24" style="margin-top: 16px;" v-if="orderInfo.description">
            <a-col :span="24">
              <div class="detail-item">
                <span class="detail-label">订单描述:</span>
                <div class="detail-value">{{ orderInfo.description }}</div>
              </div>
            </a-col>
          </a-row>

          <a-row :gutter="24" style="margin-top: 16px;" v-if="orderInfo.remark">
            <a-col :span="24">
              <div class="detail-item">
                <span class="detail-label">备注:</span>
                <div class="detail-value">{{ orderInfo.remark }}</div>
              </div>
            </a-col>
          </a-row>
        </a-card>

        <!-- 订单明细 -->
        <a-card title="订单明细" size="small" style="margin-bottom: 16px;">
          <a-table
            :columns="detailColumns"
            :dataSource="detailList"
            :pagination="false"
            rowKey="id"
            size="small"
            bordered>
            
            <template slot="subtotal" slot-scope="text, record">
              <span class="amount">¥{{ ((record.quantity * record.unitPrice) || 0).toFixed(2) }}</span>
            </template>
          </a-table>
          
          <div style="text-align: right; margin-top: 16px; font-size: 16px; font-weight: bold;">
            合计金额: <span class="total-amount">¥{{ totalDetailAmount.toFixed(2) }}</span>
          </div>
        </a-card>

        <!-- 交易记录 -->
        <a-card title="交易记录" size="small" style="margin-bottom: 16px;">
          <a-table
            :columns="transactionColumns"
            :dataSource="transactionList"
            :pagination="false"
            rowKey="id"
            size="small"
            bordered>
            
            <template slot="transactionType" slot-scope="text">
              <a-tag :color="getTransactionTypeColor(text)">
                {{ getTransactionTypeText(text) }}
              </a-tag>
            </template>

            <template slot="amount" slot-scope="text">
              <span class="amount">¥{{ (text || 0).toFixed(2) }}</span>
            </template>

            <template slot="paymentMethod" slot-scope="text">
              {{ getPaymentMethodText(text) }}
            </template>
          </a-table>
        </a-card>

        <!-- 进度跟踪 -->
        <a-card title="进度跟踪" size="small">
          <a-timeline>
            <a-timeline-item
              v-for="progress in progressList"
              :key="progress.id"
              :color="getProgressColor(progress.newStatus)">
              <div class="progress-item">
                <div class="progress-header">
                  <span class="progress-time">{{ progress.changeTime }}</span>
                  <span class="progress-operator">{{ progress.operatorName }}</span>
                </div>
                <div class="progress-content">
                  <strong>{{ progress.operationType }}</strong>
                  <span v-if="progress.oldStatus !== null && progress.newStatus !== null">
                    : {{ getStatusText(progress.oldStatus) }} → {{ getStatusText(progress.newStatus) }}
                  </span>
                </div>
                <div class="progress-detail" v-if="progress.operationContent">
                  {{ progress.operationContent }}
                </div>
                <div class="progress-reason" v-if="progress.changeReason">
                  <small>原因: {{ progress.changeReason }}</small>
                </div>
                <div class="progress-remark" v-if="progress.remark">
                  <small>备注: {{ progress.remark }}</small>
                </div>
              </div>
            </a-timeline-item>
          </a-timeline>
        </a-card>

      </div>
    </a-spin>
  </a-modal>
</template>

<script>
  import {
    getSemiProductSalesOrderById,
    getSemiProductSalesOrderDetailByOrderId,
    getSemiProductSalesOrderTransactionByOrderId,
    getSemiProductSalesOrderProgressByOrderId
  } from '@/api/oms/semiProductSalesOrder'

  export default {
    name: 'SemiProductSalesOrderDetail',
    data() {
      return {
        visible: false,
        loading: false,
        orderInfo: {},
        detailList: [],
        transactionList: [],
        progressList: [],
        detailColumns: [
          {
            title: '序号',
            dataIndex: 'index',
            width: 60,
            customRender: (text, record, index) => index + 1
          },
          {
            title: '物料名称',
            dataIndex: 'materialName',
            width: 200
          },
          {
            title: '规格型号',
            dataIndex: 'specification',
            width: 150
          },
          {
            title: '单位',
            dataIndex: 'unit',
            width: 80
          },
          {
            title: '数量',
            dataIndex: 'quantity',
            width: 100,
            align: 'right'
          },
          {
            title: '单价',
            dataIndex: 'unitPrice',
            width: 100,
            align: 'right',
            customRender: text => `¥${(text || 0).toFixed(2)}`
          },
          {
            title: '小计',
            dataIndex: 'subtotal',
            width: 120,
            align: 'right',
            scopedSlots: { customRender: 'subtotal' }
          },
          {
            title: '备注',
            dataIndex: 'remark'
          }
        ],
        transactionColumns: [
          {
            title: '交易时间',
            dataIndex: 'transactionTime',
            width: 150
          },
          {
            title: '交易类型',
            dataIndex: 'transactionType',
            width: 100,
            scopedSlots: { customRender: 'transactionType' }
          },
          {
            title: '交易金额',
            dataIndex: 'amount',
            width: 120,
            align: 'right',
            scopedSlots: { customRender: 'amount' }
          },
          {
            title: '支付方式',
            dataIndex: 'paymentMethod',
            width: 100,
            scopedSlots: { customRender: 'paymentMethod' }
          },
          {
            title: '交易人员',
            dataIndex: 'transactionPersonName',
            width: 100
          },
          {
            title: '描述',
            dataIndex: 'description'
          },
          {
            title: '凭证',
            dataIndex: 'voucher',
            width: 100
          }
        ]
      }
    },
    computed: {
      totalDetailAmount() {
        return this.detailList.reduce((sum, item) => {
          return sum + (item.quantity * item.unitPrice || 0);
        }, 0);
      }
    },
    methods: {
      showDetail(record) {
        this.visible = true;
        this.loading = true;
        this.orderInfo = {};
        this.detailList = [];
        this.transactionList = [];
        this.progressList = [];
        
        this.loadOrderDetail(record.id);
      },
      
      async loadOrderDetail(orderId) {
        try {
          // 并行加载所有数据
          const [orderRes, detailRes, transactionRes, progressRes] = await Promise.all([
            getSemiProductSalesOrderById(orderId),
            getSemiProductSalesOrderDetailByOrderId(orderId),
            getSemiProductSalesOrderTransactionByOrderId(orderId),
            getSemiProductSalesOrderProgressByOrderId(orderId)
          ]);
          
          if (orderRes.success) {
            this.orderInfo = orderRes.result || {};
          }
          
          if (detailRes.success) {
            this.detailList = detailRes.result || [];
          }
          
          if (transactionRes.success) {
            this.transactionList = transactionRes.result || [];
          }
          
          if (progressRes.success) {
            this.progressList = (progressRes.result || []).sort((a, b) => 
              new Date(b.changeTime) - new Date(a.changeTime)
            );
          }
          
        } catch (error) {
          this.$message.error('加载订单详情失败');
          console.error('加载订单详情失败:', error);
        } finally {
          this.loading = false;
        }
      },
      
      handleCancel() {
        this.visible = false;
      },
      
      getStatusText(status) {
        const statusMap = {
          0: '待审核',
          1: '审核通过-待上传',
          2: '已上传汇总单-待上传优化单',
          3: '已上传优化单-待提交审核',
          4: '待下发',
          5: '领料单待审核',
          6: '待领料',
          7: '生产中',
          8: '已完成',
          9: '已驳回',
          10: '已入库',
          11: '已发货'
        };
        return statusMap[status] || '未知状态';
      },
      
      getStatusColor(status) {
        const colorMap = {
          0: 'orange',
          1: 'blue',
          2: 'cyan',
          3: 'purple',
          4: 'geekblue',
          5: 'orange',
          6: 'lime',
          7: 'processing',
          8: 'success',
          9: 'error',
          10: 'green',
          11: 'success'
        };
        return colorMap[status] || 'default';
      },
      
      getUrgencyText(level) {
        const urgencyMap = {
          1: '普通',
          2: '紧急',
          3: '特急'
        };
        return urgencyMap[level] || '普通';
      },
      
      getUrgencyColor(level) {
        const colorMap = {
          1: 'default',
          2: 'orange',
          3: 'red'
        };
        return colorMap[level] || 'default';
      },
      
      getTransactionTypeText(type) {
        const typeMap = {
          1: '预付款',
          2: '进度款',
          3: '尾款',
          4: '退款'
        };
        return typeMap[type] || '未知';
      },
      
      getTransactionTypeColor(type) {
        const colorMap = {
          1: 'blue',
          2: 'green',
          3: 'purple',
          4: 'red'
        };
        return colorMap[type] || 'default';
      },
      
      getPaymentMethodText(method) {
        const methodMap = {
          1: '现金',
          2: '银行转账',
          3: '支票',
          4: '承兑汇票',
          5: '其他'
        };
        return methodMap[method] || '未知';
      },
      
      getProgressColor(status) {
        if (status === 8) return 'green';
        if (status === 9) return 'red';
        if ([7, 10, 11].includes(status)) return 'blue';
        return 'gray';
      }
    }
  }
</script>

<style scoped>
  .detail-container {
    max-height: 70vh;
    overflow-y: auto;
  }
  
  .detail-item {
    margin-bottom: 8px;
  }
  
  .detail-label {
    font-weight: 500;
    color: #666;
    margin-right: 8px;
    min-width: 80px;
    display: inline-block;
  }
  
  .detail-value {
    color: #333;
  }
  
  .amount {
    font-weight: 500;
    color: #1890ff;
  }
  
  .total-amount {
    font-size: 18px;
    color: #f5222d;
  }
  
  .progress-item {
    margin-bottom: 8px;
  }
  
  .progress-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
  }
  
  .progress-time {
    color: #999;
    font-size: 12px;
  }
  
  .progress-operator {
    color: #666;
    font-size: 12px;
  }
  
  .progress-content {
    margin-bottom: 4px;
  }
  
  .progress-detail {
    color: #666;
    font-size: 13px;
    margin-bottom: 2px;
  }
  
  .progress-reason,
  .progress-remark {
    color: #999;
    font-size: 12px;
    margin-bottom: 2px;
  }
</style>
